package com.ilink.teacherservice.service.tingwu;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ilink.teacherservice.mapper.FileContentMapper;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class FileService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private FileContentMapper fileContentMapper;

    private static final String UPLOAD_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";
    private static final String COMPLETION_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
    private static final String API_KEY = "sk-38b9daad5d5e46f690545046695bd6ff"; // 这里替换为你的实际API Key

    public String uploadFileAndGetId(File file) throws Exception {
        // 设置Authorization头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization", "Bearer " + API_KEY);

        // 创建 MultiValueMap 以包含文件和其他参数
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(file));
        body.add("purpose", "file-extract");

        // 创建 HttpEntity 包含请求头和请求体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送 POST 请求并获取响应
        ResponseEntity<String> response = restTemplate.exchange(UPLOAD_URL, HttpMethod.POST, requestEntity, String.class);

        // 获取响应体内容
        String result = response.getBody();

        // 解析 JSON 并获取文件 ID
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {});
        return map.get("id").toString();
    }

    public void generateCompletion(String fileId,Long filesourceId) {
        // 配置 HTTP 头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + API_KEY);

        // 系统消息
        Map<String, String> systemMessage1 = new HashMap<>();
        systemMessage1.put("role", "system");
        systemMessage1.put("content", "You are a helpful assistant.");

        Map<String, String> systemMessage2 = new HashMap<>();
        systemMessage2.put("role", "system");
        systemMessage2.put("content", "fileid://" + fileId);

        String userMessageContent1 = "请生成一段中文导读，要求内容连贯，简洁明了，能够概括文章的核心内容。请直接输出导读内容。使用json形式，introduction";
        String userMessageContent2 = "请对文章内容进行中英互译，中文部分翻译成英文，英文部分翻译成中文。请直接输出翻译内容，使用json形式，json中包含属性“English” ";
        String userMessageContent3 = "生成一个用于思维导图的结构化文本，并将其放在nodeData键的值中，不能产生任何其他内容。"+
                "nodeData的结构化文本要求："+
                "    \n  - 根节点的id必须为'root'，topic表示思维导图的主要主题。"+
                "    \n  - 子节点及其下级节点的id必须根据章节编号填写，并确保唯一性。"+
                "    \n  - 每个节点都必须包含topic字段来表示该节点的主题内容。"+
                "    \n  - 根节点可以包含一个children数组，子节点的children数组可以包含二级子节点。"+
                "    \n  - 最多支持三级子节点，即根节点下的子节点的子节点不能再包含children字段。";
        Map<String, JsonNode> contentMap = new HashMap<>();

        // 进行三次请求，每次使用不同的用户消息
        String[] userMessages = {userMessageContent1, userMessageContent2, userMessageContent3};
        String[] keys = {"introduction", "translation", "mindmap"};


        for (int i = 0; i < 3; i++) {
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", userMessages[i]);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-long");
            requestBody.put("stream", false);
            requestBody.put("messages", List.of(systemMessage1, systemMessage2, userMessage));

            // 发送请求
            String responseBody = makeRequest(COMPLETION_URL, headers, requestBody);

            try {
                JSONObject jsonResponse = new JSONObject(responseBody);
                JSONArray choicesArray = jsonResponse.getJSONArray("choices");
                if (choicesArray.length() > 0) {
                    JSONObject firstChoice = choicesArray.getJSONObject(0);
                    String content = firstChoice.getJSONObject("message").getString("content");
                    JsonNode jsonNode = convertToJson(content);
                    contentMap.put(keys[i], jsonNode);
                } else {
                    contentMap.put(keys[i], null);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                contentMap.put(keys[i], null);
            }
        }

        // 保存到数据库
        String introduction = contentMap.get("introduction") != null ? contentMap.get("introduction").toString() : "";
        String mindmap = contentMap.get("mindmap") != null ? contentMap.get("mindmap").toString() : "";

        fileContentMapper.updateFileContent(introduction, mindmap, fileId, filesourceId);
    }

//    public Map<String, JsonNode> getContent(String tongyiId) {
//        List<String> contentList = fileContentMapper.selectIntroductionTranslationMindmapByTongyiId(tongyiId);
//        Map<String, JsonNode> contentMap = new HashMap<>();
//        String introduction = contentList.size() > 0 && contentList.get(0) != null ? contentList.get(0) : "";
//        String translation = contentList.size() > 1 && contentList.get(1) != null ? contentList.get(1) : "";
//        String mindmap = contentList.size() > 2 && contentList.get(2) != null ? contentList.get(2) : "";
//        contentMap.put("introduction", convertToJson(introduction));
//        contentMap.put("translation", convertToJson(translation));
//        contentMap.put("mindmap", convertToJson(mindmap));
//        return contentMap;
//    }

    private String makeRequest(String url, HttpHeaders headers, Map<String, Object> requestBody) {
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }

    private static JsonNode convertToJson(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readTree(json);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
